package com.atzongmaotan.reggie.controller;

import com.atzongmaotan.reggie.common.BaseContext;
import com.atzongmaotan.reggie.common.R;
import com.atzongmaotan.reggie.entity.ShoppingCart;
import com.atzongmaotan.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * ClassName:    ShoppingCartController
 * Package:  com.atzongmaotan.reggie.controller
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/25 - 下午3:59
 * @Version: v1.0
 */
@RestController
@RequestMapping("shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 购物车添加数据
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart:{}",shoppingCart.toString());
        //设置用户ID,判断当前是哪个用户的购物车数据
        Long userId = BaseContext.getCurrentUserId();
        shoppingCart.setUserId(userId);
        //查询当前菜品或者套餐是否在购物车中,如果 以存在 增加 Num,不存在则新增
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        Long dishId = shoppingCart.getDishId();
        if(dishId != null){
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        }else {
            Long setmealId = shoppingCart.getSetmealId();
            queryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        ShoppingCart cartData = shoppingCartService.getOne(queryWrapper);
        if(Objects.isNull(cartData)){
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            cartData = shoppingCart;
        }else{
            cartData.setNumber(cartData.getNumber()+1);
            shoppingCartService.updateById(cartData);
        }
        return R.success(cartData);
    }
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentUserId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        return R.success(shoppingCartService.list(queryWrapper));
    }

    @DeleteMapping("clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentUserId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }
}
